package org.example.threadorder;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhengdp
 * @Description 线程顺序控制（wait/notify版本） 交替输出 abc
 * @Date 2022/11/9 22:18
 * @Created by zhengdp
 */
@Slf4j(topic = "c.ThreadOrderWaitNotify")
public class ThreadOrderWaitNofity2 {
    public static void main(String[] args) {
        WaitNotify wn = new WaitNotify(1,5);
        new Thread(() -> {
            wn.print("a",1,2);
        },"t1").start();

        new Thread(() -> {
            wn.print("b",2,3);
        },"t2").start();

        new Thread(() -> {
            wn.print("c",3,1);
        },"t3").start();
    }


}

@Data
@AllArgsConstructor
class WaitNotify {
    // 等待标记
    private int flag;
    // 循环次数
    private int loopNumber;

    public void print(String str,int waitFlag,int nextFlag) {
        for(int i = 0;i<loopNumber;i++){
            synchronized (this){
                while(flag != waitFlag){
                    // 进入等待
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
                System.out.print(str);
                // 修改flag ,指定下一个输出的线程
                flag = nextFlag;
                this.notifyAll();
            }
        }
    }
}
